import json
from django import forms
from django.shortcuts import render, redirect, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse

from web import models
from web.utils.bootstrip import BootstrapModelForm
from web.utils.pagination import Pagination


class TaskModelForm(BootstrapModelForm):
    class Meta:
        model = models.Task
        fields = "__all__"
        widgets = {
            "detail": forms.TextInput
        }


def task_list(request):
    """任务列表"""
    # 取数据库数据
    queryset = models.Task.objects.all().order_by('-id')
    # 分页
    page_object = Pagination(request, queryset, page_size=2)
    form = TaskModelForm()
    context = {
        'form': form,
        'queryset': page_object.page_queryset,
        'page_string': page_object.html()
    }
    return render(request, 'task_list.html', context)


@csrf_exempt
def task_ajax(request):
    """测试ajax使用"""
    print(request.POST)
    data_dict = {"status": True, "data": [11, 22, 33, 44]}
    return HttpResponse(json.dumps(data_dict))


@csrf_exempt
def task_add(request):
    """添加任务"""
    print(request.POST)
    # 1 对用户发送过来的数据进行表单的校验（利用ModelForm）
    form = TaskModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        # 校验通过，通过Ajax请求返回一个JSON
        data_dict = {'status': True}
        return HttpResponse(json.dumps(data_dict))
    # 验证失败,给出错误信息
    data_dict = {'status': False, 'error': form.errors}
    return HttpResponse(json.dumps(data_dict, ensure_ascii=False))
